<template>
	<div class="payment-methods-card">
		<template v-if="list && list.length > 0">
			<div v-for="(item, index) in list" :key="index" class="payment-method-item">
				<div class="payment-methods-cell flex_between">
					<div class="method-info" @click="printDetail(item)">
						<div :class="['method-name', 'ellipsis', { 'checkbox-checked': item.id == currentId }]"
							:title="item.title">
							<span>{{ item.title }}</span>
							<span v-if="item.id == currentId" class="font_black9"
								style="font-size: 11px; font-weight: normal;">（当前编辑）</span>
						</div>
					</div>
					<div class="payment-actions">
						<div class="custom-checkbox" :class="{ 'checkbox-checked': item.id == currentId }">
							<span v-if="item.id == currentUseId" class="font_green bold">正在使用</span>
							<el-dropdown v-else size="small" @command="removePrintTpl" trigger="click">
								<span class="el-dropdown-link">
									<i class="el-icon-more font_black9"></i>
								</span>
								<el-dropdown-menu slot="dropdown" size="small">
									<el-dropdown-item :command="{ ...item, action: 'remove' }"> 删 除 </el-dropdown-item>
									<el-dropdown-item :command="{ ...item, action: 'use' }"> 使用模版 </el-dropdown-item>
								</el-dropdown-menu>
							</el-dropdown>
						</div>
					</div>
				</div>
			</div>
		</template>
		<template v-if="list && list.length == 0 && isDlo">
			<el-empty image-size="80"></el-empty>
		</template>
	</div>
</template>
<script setup>
import {
	ref,
	onMounted,
	onBeforeUnmount,
	nextTick,
	defineExpose,
	computed,
	defineProps,
	getCurrentInstance,
	defineEmits,
	inject,
	watch
} from '@vue/composition-api'
const { proxy } = getCurrentInstance()
import config from "@/js/conf/Config.js"

// 1. 首先定义所有响应式变量
const props = defineProps({
	currentMenu: {
		type: Object,
		default: () => { }
	},
	propData: {
		type: Object,
		default: () => { }
	}
})

const emit = defineEmits(['change'])
const currentId = ref('')	// 当前激活的模版
const currentUseId = ref('') // 当前使用的模版
const list = ref([])
const isDlo = ref(false)

proxy.$eventBus.$on('compsetPrintTplSave', (item) => {
	currentId.value = item?.id;
	emit('change', currentId.value)
	getPrintTplLs()
})

const printModuleSet = inject('printModuleSet', ref({}))
const getPrintTplLs = async () => {
	isDlo.value = false
	try {
		let res = await proxy.$api({
			url: config.compset_print_tpl_ls, data: {
				type: props.currentMenu.id
			}
		})
		if (res.status == 1) {
			list.value = res.data
			currentId.value = res.data[0]?.id || ''
			emit('change', currentId.value)
		} else {
			list.value = []
		}
		setIsDlo()
	} catch (error) {
		console.error('获取打印模板列表失败:', error)
	}
}

const setIsDlo = (val) => {
	setTimeout(() => {
		isDlo.value = true
	}, 1000)
}

const printDetail = (item) => {
	currentId.value = item.id;
	emit('change', currentId.value)
	// submitHandle(item)
}

const choosePrintTplDate = ref({})
const removePrintTpl = async (command) => {
	console.log('removePrintTpl-command=', command)
	const { action, ...item } = command
	console.log('action类型:', action)
	console.log('item数据:', item)
	choosePrintTplDate.value = item
	if (action == 'remove') {
		try {
			proxy.$confirm('确定删除吗？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			}).then(async () => {
				let res = await proxy.$api({ url: config.compset_print_tpl_del, data: { id: item.id } });
				if (res.status == 1) {
					proxy.$message({
						message: '删除成功',
						type: 'success',
					})
					getPrintTplLs()
				} else {
					proxy.$message({
						message: res.msg || '删除失败',
						type: 'error',
					})
				}
			})
		} catch (error) {
			// 用户取消删除或发生其他错误
			console.log('删除操作取消或失败:', error)
		}
	} else if (action == 'use') {
		// 处理使用模板的逻辑
		console.log('使用模板:', item)
		// 这里可以添加使用模板的代码
		submitHandle(item)
	}
}

// 提交保存
const submitHandle = async (item) => {
	let idType = props.currentMenu.id
	let propData = props.propData
	let params = {
		id_cg: idType == 'cg' ? item.id : propData.tpl['cg']?.id,
		id_ck: idType == 'ck' ? item.id : propData.tpl['ck']?.id,
		id_db: idType == 'db' ? item.id : propData.tpl['db']?.id,
		id_rk: idType == 'rk' ? item.id : propData.tpl['rk']?.id,
		id_xs: idType == 'xs' ? item.id : propData.tpl['xs']?.id,
		id_yy: idType == 'yy' ? item.id : propData.tpl['yy']?.id,
		id_dz: propData.tpl['dz']?.id,
		paper_w: propData.paper_w,
		qrcode_i: propData.qrcode_i,
		txt_img: propData.txt_img
	}
	try {
		let res = await proxy.$api({ url: config.compset_print_set_save, data: params })
		if (res.status == 1) {
			proxy.$eventBus.$emit('changeTempSetting', choosePrintTplDate.value)
		}
	} catch (error) { }
}

// 5. 监听注入数据的变化
watch(() => printModuleSet.value, (newValue) => {
	// 当数据变化时，执行相关逻辑
	if (newValue && newValue.id) {
		getPrintTplLs()
		// currentId.value = newValue.id
		currentUseId.value = newValue.id
		emit('change', currentId.value)
	}
}, { immediate: true })

// 6. 合并的 onMounted 钩子
onMounted(() => {
	// getPrintTplLs()
	// if (printModuleSet.value && printModuleSet.value.id) {
	// 	currentId.value = printModuleSet.value.id
	// }
})

// 在组件卸载前移除事件监听器
// onBeforeUnmount(() => {
//   proxy.$eventBus.$off('compsetPrintTplSave')
// })

defineExpose({})

</script>
<style scoped lang="scss">
.payment-methods-cell {
	padding: 10px 0;
	border-bottom: 1px solid #f0f2f5;
	transition: background-color 0.2s ease;
	background-color: #fff;
}

.method-info {
	display: flex;
	flex-direction: column;
	cursor: pointer;
	box-sizing: border-box;
}

.method-name {
	font-weight: 500;
	color: #303133;
	font-size: 14px;
	width: 160px;
}

.custom-checkbox {
	// .el-icon-check {
	// 	font-size: 18px;
	// 	color: #3b73ed;
	// 	font-weight: bold;
	// }
}

.checkbox-checked {
	color: #3b73ed;
	font-weight: 600;
}
</style>